package com.xjtu.se.homework.client.feedback.controller;

import com.fasterxml.jackson.annotation.JsonFormat;
import com.xjtu.se.homework.client.feedback.dto.BackDto;
import com.xjtu.se.homework.client.feedback.sevice.UserFeedbackService;
import com.xjtu.se.homework.client.mainPage.PicDto;
import com.xjtu.se.homework.common.Result;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
import java.sql.Date;
import java.util.ArrayList;

import static com.xjtu.se.homework.client.mainPage.PicAPI.getUUIDFileName;

@RestController
@RequestMapping("/helper/feedback")
public class UserFeedBackAPI {
    private static String filePath = "C:/Users/wyh/Desktop/helper-master/homework_helper/uploads";

    @Resource
    private UserFeedbackService service;

    @PostMapping("/upload")
    public Result upload(@RequestParam("u_id") String u_id,
                         @RequestParam("f_image") ArrayList<MultipartFile> f_image,
                         @RequestParam("u_email") String u_email,
                         @RequestParam("f_id") String f_id,
                         @RequestParam("f_infor") String f_infor) {
        String imagePath = "";
        for (int i = 0; i < f_image.size(); i++) {
            MultipartFile file = f_image.get(i);
            if (file.isEmpty()) {
                System.out.println("文件为空");
            }
            System.out.println("文件开始上传");
            String fileName = getUUIDFileName(file.getOriginalFilename());  // 文件名
            System.out.println(fileName);
            //上传到服务器之中了

            File dest = new File(filePath + "/" + fileName);
            if (!dest.getParentFile().exists()) {
                dest.getParentFile().mkdirs();
                try {
                    dest.createNewFile();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                file.transferTo(dest);
            } catch (IOException e) {
                e.printStackTrace();
            }
            if (i == f_image.size() - 1) imagePath += fileName;
            else imagePath += fileName + ",";
        }

        BackDto dto = new BackDto();
        dto.setF_id(f_id);
        dto.setF_image(imagePath);
        dto.setF_infor(f_infor);
        dto.setU_email(u_email);
        dto.setU_id(u_id);
        Date time = new Date(System.currentTimeMillis());
        dto.setF_time(time);
        dto.setF_status("待处理");
        service.upload(dto);


        return Result.success("success");
    }
}
